package com.leo;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

/**
 * @ClassName ChoiceBoxDemo
 * @Description
 * @Author wangss
 * @date 2020.05.24 21:32
 * @Version 1.0
 */
public class ChoiceBoxDemo extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        AnchorPane anchorPane = new AnchorPane();
        anchorPane.setStyle("-fx-background-color: #e7eeea");
        Scene scene = new Scene(anchorPane);

        ChoiceBox<String> choiceBox = new ChoiceBox<>();
        choiceBox.getItems().addAll("item1", "item2", "item3");

        choiceBox.setValue("item2");
//        choiceBox.getSelectionModel().select("item2");
        // 选择上一个
//        choiceBox.getSelectionModel().selectPrevious();

        choiceBox.setPrefWidth(100d);
        AnchorPane.setTopAnchor(choiceBox, 10d);
        AnchorPane.setLeftAnchor(choiceBox, 10d);
        anchorPane.getChildren().addAll(choiceBox);

        primaryStage.setScene(scene);
        primaryStage.setTitle("choicebox");
        primaryStage.setWidth(625d);
        primaryStage.setHeight(500d);
        primaryStage.setResizable(false);
        primaryStage.show();

        choiceBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                System.out.println(newValue);
            }
        });
    }
}
